import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { inventoryCheck, inventoryCheckItems, products } from '@/lib/schema';
import { eq } from 'drizzle-orm';

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const checkId = parseInt(params.id);
    
    // 获取盘点单基本信息
    const check = await db
      .select()
      .from(inventoryCheck)
      .where(eq(inventoryCheck.id, checkId))
      .limit(1);

    if (check.length === 0) {
      return NextResponse.json(
        { error: '盘点单不存在' },
        { status: 404 }
      );
    }

    // 获取盘点明细
    const checkItems = await db
      .select({
        id: inventoryCheckItems.id,
        productId: inventoryCheckItems.productId,
        systemQuantity: inventoryCheckItems.systemQuantity,
        actualQuantity: inventoryCheckItems.actualQuantity,
        discrepancy: inventoryCheckItems.discrepancy,
        notes: inventoryCheckItems.notes,
        checkedBy: inventoryCheckItems.checkedBy,
        checkedAt: inventoryCheckItems.checkedAt,
        productName: products.name,
        productSku: products.sku,
      })
      .from(inventoryCheckItems)
      .leftJoin(products, eq(inventoryCheckItems.productId, products.id))
      .where(eq(inventoryCheckItems.checkId, checkId));

    return NextResponse.json({
      ...check[0],
      items: checkItems,
    });

  } catch (error) {
    console.error('获取盘点详情失败:', error);
    return NextResponse.json(
      { error: '获取盘点详情失败' },
      { status: 500 }
    );
  }
}